<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Block_Post_Filter_Tag extends Block_Post_Filter_Abstract {

	private $_from = 'post_tag pt';	// from part in the select statement
	
	public function __construct() {
		$this->_requestVar = 'tags';
		$this->setTemplate('post/filter/tag');
	}
	
	public function apply() {
		if (App::get($this->getRequestVar())) {
			// get applied values
			$tagids = $this->stringToValues(App::get($this->_requestVar));
			$this->_appliedValues = $tagids;
			
			// append filter to collection
			$select = $this->getLayer()->getCollection()->getSelect();
			$cond = sprintf('pt.tag_id IN(%s)', implode(',' ,$tagids));
			$select->join($this->_from, 'post.id = pt.post_id AND '.$cond)
				->group('post.id')->having('COUNT(DISTINCT pt.tag_id) = '.count($tagids));
		}
	}
	
	public function getItems() {
		$select = clone $this->getLayer()->getCollection()->getSelect();
		$select->setPart(Core_Db_Select::COLUMNS, array('post.id'))
			->resetPart(Core_Db_Select::LIMIT)
			->resetPart(Core_Db_Select::ORDER);
		
		$select2 = 'SELECT tag.*, COUNT(pt2.post_id) as post_count '.
			'FROM tag JOIN post_tag pt2 ON pt2.tag_id = tag.id '.
			'WHERE pt2.post_id IN ('.(string)$select.') '.
			'GROUP  BY tag.id';
		$rows = App::db()->query($select2)->result_array();
		
		// prepare filter items
		$items = array();
		foreach($rows as $row) {
			$item = array(
				'label' => $row['name'],
				'value' => $row['id'],
				'count' => $row['post_count'],
				'selected' => in_array($row['id'], $this->getAppliedValues()),
				'url' => $this->getItemUrl($row['id'])
			);
			array_push($items, $item);
		}
		return $items;
	}
	
	public function getItemUrl($value) {
		$values = $this->getAppliedValues();
		if (!in_array($value, $this->getAppliedValues())) {	// check if value not applied
			array_push($values, $value);
		} else if (($key = array_search($value, $values)) !== false) {
			unset($values[$key]);
		}
		$query = App::get();
		$query[$this->getRequestVar()] = $this->valuesToString($values);
		return App::url('*/*', array('_query' => $query));
	}
}